/**
 * 
 */
package com.fnic.pearl.scheduler.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.SchedulerConfig;
import com.fnic.pearl.scheduler.constant.CondHeaderField;
import com.fnic.pearl.scheduler.constant.SchedulerUrl;
import com.fnic.pearl.scheduler.mod.ActiveToManager;
import com.fnic.pearl.scheduler.mod.ProbeStatusManager;
import com.fnic.pearl.scheduler.model.ProbeStatus;
import com.fnic.pearl.scheduler.model.VersionUpdateStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 升级状态
 * 
 * @author HuHaiyang
 * @date 2014年2月17日
 */
public class VersionUpdateStatusServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static Logger LOG = Logger.getLogger(VersionUpdateStatusServlet.class);
    private Gson gson = new GsonBuilder()
                            .excludeFieldsWithoutExposeAnnotation()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String[] values = request.getParameterValues(CondHeaderField.COND_PROBE_ID);
        if (values == null || values.length != 1)
        {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        int probeId = 0;
        try
        {
            probeId = Integer.valueOf(values[0]);
        }
        catch (NumberFormatException e)
        {
            LOG.warn("probeId format error: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        ProbeStatus ps = ProbeStatusManager.getInstance().get(probeId);
        if (ps == null || ps.getStatus() != ProbeStatus.S_LOGIN)
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ;
        }
        
        VersionUpdateStatus us = null;
        try
        {
        	BufferedReader br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
        	StringBuffer sb = new StringBuffer();
        	String line = "";
        	while((line=br.readLine())!=null){
        		sb.append(line);
        	}
        	System.out.println(sb.toString());
            us = gson.fromJson(sb.toString(), VersionUpdateStatus.class);
        }
        catch (Exception e)
        {
            LOG.warn("update status parse exception - " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        if (us == null)
        {
            LOG.warn("update status is null!");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        // 直接转发给管理节点
        
        //PROBE_UPDATE_STATUS
        
//        String urlUpdateStatus = new StringBuilder().append("http://")
//                .append(SchedulerConfig.getInstance().getManagerIp()).append(":").append(SchedulerConfig.getInstance().getManagerManagePort())
//                .append(SchedulerUrl.VERSION_UPDATE_STATUS)
//                .append("?").append(CondHeaderField.COND_SCHEDULER_ID).append("=")
//                .append(SchedulerConfig.getInstance().getSchedulerId())
//                .toString();
        //更新接口
        
        String urlUpdateStatus = new StringBuilder().append("http://")
                .append(SchedulerConfig.getInstance().getManagerIp()).append(":").append(SchedulerConfig.getInstance().getManagerPort())
                .append(SchedulerUrl.PROBE_UPDATE_STATUS)
                .append("?").append(CondHeaderField.COND_SCHEDULER_ID).append("=")
                .append(SchedulerConfig.getInstance().getSchedulerId())
                .toString();
        System.out.println("urlUpdateStatus:"+urlUpdateStatus);
        HttpPost post = new HttpPost(urlUpdateStatus);
        try
        {
            String json = gson.toJson(us);
            StringEntity se = new StringEntity(json);
            post.setEntity(se);
            LOG.info("send version update status to manager: " + json);
        }
        catch (UnsupportedEncodingException e)
        {
            LOG.warn("encoding testask status to json ex: " + e.getMessage());
        }
        finally
        {
            post.releaseConnection();
        }
        
        ActiveToManager.getInstance().putRequest(post);
        
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
